import {TankImage} from "./const.ts";

export class GameMap {
    map: number[][]

    constructor(map: number[][]) {
        this.map = map
    }

    render(ctx: CanvasRenderingContext2D) {
        renderMap(this.map, ctx)
    }

    // 模型和地图的碰撞检测
    impact(x: number, y:number, level: number) {
        if (level > this.map[x][y]){
            this.map[x][y] = 0
        }

    }

}


const imageSrcPos = {
    0: [256, 0, 8, 8],
    1: [256, 0, 8, 8],
    2: [256, 16, 8, 8],
    3: [256, 32, 8, 8],
    4: [272, 32, 8, 8],
    5: [288, 32, 8, 8],
} as { [key: number]: number[] }

function renderMap(map: number[][], ctx: CanvasRenderingContext2D) {
    const tileSize = 16;

    for (let i = 0; i < map.length; i++) {
        for (let j = 0; j < map[i].length; j++) {
            if (map[i][j] === 0) continue;
            let pos = imageSrcPos[map[i][j]];
            ctx.drawImage(TankImage, pos[0], pos[1], pos[2], pos[3], tileSize * j, tileSize * i, tileSize, tileSize);
        }
    }
}


export function isAccessible(x: number, y: number, width: number, height: number, map: number[][]) {
    let x1 = Math.floor((x - (width / 2)) / 32)
    let x2 = Math.floor((x + (width / 2) - 1) / 32)
    let y1 = Math.floor((y - (height / 2)) / 32)
    let y2 = Math.floor((y + (height / 2) - 1) / 32)

    if (x1 < 0 || x2 >= map[0].length || y1 < 0 || y2 >= map.length) {
        return false
    } else {
        for (let i = x1; i <= x2; i++) {
            for (let j = y1; j <= y2; j++) {
                if (map[j][i] !== 0) {
                    return false
                }
            }
        }
        return true
    }
}
